const { WorkOrder, Employee, TaskAssignment } = require('../../database/index')
const { getExecutedSql } = require('../../logger');
const Sequelize = require('sequelize')
// 导出
module.exports = async (req, res) =>
{
    const operation = req.params.operation;
    const { searchType, pageNum_w = 1, // 默认页码为1
        pageSize_w = 5, pageNum_u = 1, // 默认页码为1
        pageSize_u = 5, workOrderName, workOrderStatus, income, workOrderDescription, dueDate, assignedUserID, createdUserID, workOrderID } = req.body
    try {
        switch (operation) {
            case 'create':
                // // 根据客户端传递过来的 用户名 查询 数据库 中 是否 存在这用户名
                const state = {
                    WorkOrderName: workOrderName,
                    WorkOrderDescription: workOrderDescription,
                    CreatedDate: new Date(),
                    DueDate: dueDate,  //到期日
                    Status: 0,
                    AssignedUserID: 3,  //分配者ID
                    Income: income,
                    CreatedUserID: createdUserID  //创建者ID
                }
                const newWorkOrderData = await WorkOrder.create(state)
                const data = await WorkOrder.findOne({
                    where: {
                        WorkOrderID: newWorkOrderData.WorkOrderID
                    }
                })
                res.status(200).send({
                    data,
                    meta: {
                        msg: "创建成功",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case 'read':
                // 实现分页
                let whereCondition = {}; // 默认查询条件为空对象
                if (searchType === "exact" && workOrderName) {
                    // 执行精确搜索
                    whereCondition = { WorkOrderName: { [Sequelize.Op.eq]: workOrderName } };
                } else if (searchType === "fuzzy" && workOrderName) {
                    // 执行模糊搜索
                    whereCondition = { WorkOrderName: { [Sequelize.Op.like]: `%${workOrderName}%` } };
                }
                // 计算偏移量和页大小
                const offset_w = (pageNum_w - 1) * pageSize_w;
                const offset_u = (pageNum_u - 1) * pageSize_u;


                // 查询已分配的工单
                const assignedWorkOrders = await TaskAssignment.findAndCountAll({
                    limit: Number(pageSize_w),
                    offset: Number(offset_w),
                    include: [
                        {
                            model: WorkOrder,
                            where: whereCondition,
                            as: 'workOrderData',
                            attributes: ['WorkOrderName', 'Status', 'Income', 'WorkOrderDescription'],
                            include: [
                                {
                                    model: Employee,
                                    as: 'createdUserName',
                                    attributes: ['Name', 'EmployeeID'],
                                    required: false, // 允许没有匹配的员工信息
                                },
                            ],
                        },
                        {
                            model: Employee,
                            as: 'assignedToUserName',
                            attributes: ['Name', 'EmployeeID'],
                        },
                    ],
                });

                // 查询未分配的工单
                const unassignedWorkOrderData = await WorkOrder.findAndCountAll({
                    limit: Number(pageSize_u),
                    offset: Number(offset_u),
                    where: {
                        [Sequelize.Op.and]: [
                            {
                                WorkOrderID: {
                                    [Sequelize.Op.notIn]: Sequelize.literal('(SELECT WorkOrderID FROM TaskAssignment)'),
                                }
                            },
                            whereCondition
                        ]
                    },
                });

                const totalAssignedWorkOrders = assignedWorkOrders.count;
                const totalUnassignedWorkOrders = unassignedWorkOrderData.count;

                res.status(200).send({
                    data: {
                        workOrderData: {
                            workOrderData: assignedWorkOrders.rows, //已经分配的工单
                            total: totalAssignedWorkOrders,
                            pageSize: Number(pageSize_w),
                            pageNum: Number(pageNum_w),
                        },
                        unassignedWorkOrderData: {
                            unassignedWorkOrderData: unassignedWorkOrderData.rows,
                            total: totalUnassignedWorkOrders,
                            pageSize: Number(pageSize_u),
                            pageNum: Number(pageNum_u),
                        }
                    },
                    meta: {
                        msg: "获取成功！",
                        status: 200
                    },
                    sql: getExecutedSql()
                });

                break;
            case 'update':
                const stateData = {
                    WorkOrderName: workOrderName,
                    WorkOrderDescription: workOrderDescription,
                    CreatedDate: new Date(),
                    DueDate: dueDate,  //到期日
                    Status: workOrderStatus,
                    Income: income,
                    AssignedUserID: assignedUserID,  //分配者ID
                    CreatedUserID: createdUserID  //创建者ID
                }
                const upWorkOrderIDData = await WorkOrder.update(stateData, { where: { WorkOrderID: workOrderID } },)
                res.status(200).send({
                    meta: {
                        msg: "编辑成功",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case 'readAll':
                // 查询已分配的工单
                const tableData = await TaskAssignment.findAndCountAll({
                    include: [
                        {
                            model: WorkOrder,
                            as: 'workOrderData',
                            attributes: ['WorkOrderName', 'Status', 'Income', 'WorkOrderDescription'],
                            include: [
                                {
                                    model: Employee,
                                    as: 'createdUserName',
                                    attributes: ['Name', 'EmployeeID'],
                                    required: false, // 允许没有匹配的员工信息
                                },
                            ],
                        },
                        {
                            model: Employee,
                            as: 'assignedToUserName',
                            attributes: ['Name', 'EmployeeID'],
                        },
                    ],
                });
                // 查询未分配的工单
                const untableData = await WorkOrder.findAndCountAll({
                    where: {
                        [Sequelize.Op.and]: [
                            {
                                WorkOrderID: {
                                    [Sequelize.Op.notIn]: Sequelize.literal('(SELECT WorkOrderID FROM TaskAssignment)'),
                                }
                            }
                        ]
                    },
                });
                res.status(200).send({
                    data: {
                        tableData,
                        untableData
                    },
                    meta: {
                        msg: "获取成功",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case 'delete':
                const delData = await WorkOrder.destroy({ where: { WorkOrderID: workOrderID } })
                res.status(200).send({
                    meta: {
                        msg: "删除成功",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break
            case 'findAllWorkOrderList':
                const workOrderNames = await WorkOrder.findAll({
                    attributes: ['WorkOrderName'] // 只选择用户名字段
                });
                const workOrderNameList = workOrderNames.map(dep => dep.WorkOrderName);
                // 打印sql语句
                res.status(200).send({
                    workOrderNameList,
                    meta: {
                        msg: "获取成功！",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case 'findWorkOrderAndID':
                const workOrderAndID = await Employee.findAll({
                    attributes: ['Name', "EmployeeID"] // 只选择用户名字段
                });
                // 打印sql语句
                res.status(200).send({
                    workOrderAndID,
                    meta: {
                        msg: "获取成功！",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            default:
                break;
        }

    } catch (error) {
        res.status(500).send({ message: 'Internal server error', error: error.message });
    }
}